package com.mission.schedule.my160920.adapter;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.mission.schedule.R;
import com.mission.schedule.applcation.App;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.my160920.FrendBean;
import com.mission.schedule.my160920.FrendLyActivity;
import com.mission.schedule.my160920.NewEndTaskActivity;
import com.mission.schedule.my160920.NewMyFragment;
import com.mission.schedule.my160920.SwipeLayout;
import com.mission.schedule.my160920.bean.FriendDownAllScheduleBean;
import com.mission.schedule.my160920.bean.LyNewNumBean;
import com.mission.schedule.my160920.picker.DatePicker;
import com.mission.schedule.my160920.picker.TimePicker;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.UriUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by liwei on 16/9/18.
 */
public class FindFrendAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnTouchListener {

    //四种不同的ViewType类型，事先用常量定义好
    public static final int VIEW_TYPE_ONE = 1;
    public static final int VIEW_TYPE_TWO = 2;
    public static final int VIEW_TYPE_THREE = 3;
    public static final int VIEW_TYPE_FOUR = 4;

    private List<FrendBean> frendBeanList;
    //checkbox记录
    private List<Integer> checkPositionlist;

    private Context context;

    private int cpost = 1;
    private int displayAlarm = 0;

    final ProgressUtil progressUtil = new ProgressUtil();


    public FindFrendAdapter(List<FrendBean> frendBeanList, Context con, Handler handler) {
        this.frendBeanList = frendBeanList;
        this.context = con;
        checkPositionlist = new ArrayList<>();
        this.handler = handler;
    }

    float down_x = 0;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            if (event.getX() - down_x > 0) {
                return true;
            }
        }
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            down_x = event.getX();
        }
        return false;
    }

    /**
     * 顶部布局
     */
    public class ViewHolderOne extends RecyclerView.ViewHolder {

        ImageView icon;
        TextView name, mess;

        LinearLayout yc_ll, add_lll;
        View vt;


        public ViewHolderOne(View v) {
            super(v);
            add_lll = (LinearLayout) v.findViewById(R.id.add_lll);
            icon = (ImageView) v.findViewById(R.id.f_icon);
            name = (TextView) v.findViewById(R.id.f_name);
            mess = (TextView) v.findViewById(R.id.f_mes);
            yc_ll = (LinearLayout) v.findViewById(R.id.yc_ll);
            vt = (View) v.findViewById(R.id.vt);
        }
    }

    /**
     * 中间布局
     */
    public class ViewHolderTwo extends RecyclerView.ViewHolder {

        LinearLayout llc, l_c, item_ll;
        //侧滑布局
        public SwipeLayout swipeLayout;
        private CheckBox radioButton;
        private TextView message, downnum, downstate, order, ztt;
        private boolean fb = false;
        private ImageView calender_type, zti;

        public ViewHolderTwo(View v) {
            super(v);
            swipeLayout = (SwipeLayout) v.findViewById(R.id.swip);
            //添加侧滑
            SwipeLayout.addSwipeView(swipeLayout);

            llc = (LinearLayout) v.findViewById(R.id.llc);
            radioButton = (CheckBox) v.findViewById(R.id.radioi);
            radioButton.setTag(v);
            radioButton.setChecked(false);
            message = (TextView) v.findViewById(R.id.message);
            downnum = (TextView) v.findViewById(R.id.downnum);
            downstate = (TextView) v.findViewById(R.id.downstate);
            order = (TextView) v.findViewById(R.id.order);
            l_c = (LinearLayout) v.findViewById(R.id.layout_content);
            item_ll = (LinearLayout) v.findViewById(R.id.item_ll);
            calender_type = (ImageView) v.findViewById(R.id.calender_type);
            ztt = (TextView) v.findViewById(R.id.ztt);
            zti = (ImageView) v.findViewById(R.id.zti);

        }
    }

    /**
     * 底部布局
     */
    public class ViewHolderThree extends RecyclerView.ViewHolder {

        LinearLayout llc, l_c, item_ll;
        //侧滑布局
        public SwipeLayout swipeLayout;
        private CheckBox radioButton;
        private TextView message, downnum, downstate, order, ztt;
        private boolean fb = false;
        private ImageView calender_type, zti;

        public ViewHolderThree(View v) {
            super(v);
            swipeLayout = (SwipeLayout) v.findViewById(R.id.swip);
            //添加侧滑
            SwipeLayout.addSwipeView(swipeLayout);

            llc = (LinearLayout) v.findViewById(R.id.llc);
            radioButton = (CheckBox) v.findViewById(R.id.radiof);
            radioButton.setTag(v);
            radioButton.setChecked(false);
            message = (TextView) v.findViewById(R.id.message);
            downnum = (TextView) v.findViewById(R.id.downnum);
            downstate = (TextView) v.findViewById(R.id.downstate);
            l_c = (LinearLayout) v.findViewById(R.id.layout_contents);
            item_ll = (LinearLayout) v.findViewById(R.id.item_ll);
            order = (TextView) v.findViewById(R.id.order);
            calender_type = (ImageView) v.findViewById(R.id.calender_type);
            ztt = (TextView) v.findViewById(R.id.ztt);
            zti = (ImageView) v.findViewById(R.id.zti);
        }
    }

    /**
     * 添加任务布局
     */
    public class ViewHolderFour extends RecyclerView.ViewHolder {

        TextView add;
        LinearLayout bottom_l;

        public ViewHolderFour(View v) {
            super(v);
            add = (TextView) v.findViewById(R.id.add_txt);
            bottom_l = (LinearLayout) v.findViewById(R.id.bottom_l);
        }
    }

    /**
     * 添加用户(暂时不用)
     *
     * @param frendBeanLists
     */
    public void addFindFrend(List<FrendBean> frendBeanLists) {
        for (int i = 0; i < frendBeanLists.size(); i++) {
            for (int j = 0; j < frendBeanList.size(); j++) {
                if (frendBeanLists.get(i).getUid().equals(frendBeanList.get(j).getUid())) {
                    frendBeanList.add(i + 1, frendBeanLists.get(i));
//                    send2(i+1,002);
                } else {
                    frendBeanLists.add(frendBeanLists.get(i));
//                    send2(0,002);
                }

            }
        }

    }

    /**
     * 添加item，并选择不同的item进行添加
     *
     * @param cpid
     * @param uid
     * @param time
     * @param calendId
     * @param name
     * @param message
     * @param nickname
     * @param uPortrait
     * @param position
     */
    private void addData(String cpid, String uid, String time, String calendId, String name, String message, String nickname, String uPortrait, int position) {
        if (frendBeanList.size() > position + 1) {
            //判断当前position的下一项类型
            if (frendBeanList.get(position + 1).getViewType() == 3 || frendBeanList.get(position + 1).getViewType() == 2) {

                addItem(cpid, uid, time, calendId, name, message, nickname, uPortrait, 2, position + 1);

                notifyItemInserted(position + 1);
//                notifyItemRangeChanged(position + 1, frendBeanList.size() - (position + 1));

            } else if (frendBeanList.get(position + 1).getViewType() == 4) {
                addItem(cpid, uid, time, calendId, name, message, nickname, uPortrait, 3, position + 1);

                notifyItemChanged(position);
                notifyItemInserted(position + 1);
//                notifyItemRangeChanged(position + 1, frendBeanList.size() - (position + 1));

                removeAdd(position + 1);
            } else if (frendBeanList.get(position - 1).getViewType() == 1) {
                addItem(cpid, uid, time, calendId, name, message, nickname, uPortrait, 3, position);

                notifyItemChanged(position - 1);
                notifyItemInserted(position);
//                notifyItemRangeChanged(position, frendBeanList.size() - (position));

                removeAdd(position);
            }
//            notifyDataSetChanged();
        }
        send(5, frendBeanList.get(position).getF_cpId());
        progressUtil.dismiss();
    }


    /**
     * 添加"添加任务"view
     *
     * @param position
     */
    private void addBean(int position) {
        FrendBean frendBean = new FrendBean();
        frendBean.setUid(frendBeanList.get(position - 1).getF_uid());
        frendBean.setF_uNickName(frendBeanList.get(position - 1).getF_uNickName());
        frendBean.setF_uPortrait(frendBeanList.get(position - 1).getF_uPortrait());
        frendBean.setF_cpId(frendBeanList.get(position - 1).getF_cpId());
        frendBean.setViewType(4);
        frendBeanList.add(position, frendBean);
    }

    /**
     * 删除item，根据不同item删除
     *
     * @param position
     */
    private void removeData(int position) {

        if (frendBeanList.get(position).getViewType() == 3) {
            frendBeanList.remove(position);
            notifyItemRemoved(position);
//            notifyItemRangeRemoved(position, frendBeanList.size() - position);
            if (frendBeanList.get(position - 1).getViewType() == 2) {

                frendBeanList.get(position - 1).setViewType(3);
                notifyItemChanged(position - 1);

            } else if (frendBeanList.get(position - 1).getViewType() == 1) {

                addBean(position);

                notifyItemChanged(position - 1);
                notifyItemInserted(position);

                send(9,"1");
//                notifyItemRangeChanged(position, frendBeanList.size() - position);
            }

        } else if (frendBeanList.get(position).getViewType() == 2) {
            frendBeanList.remove(position);
            notifyItemRemoved(position);
//            notifyItemRangeRemoved(position, frendBeanList.size() - position);
        }

        progressUtil.dismiss();
//        notifyDataSetChanged();
    }

    /**
     * 删除添加任务item
     *
     * @param position
     */
    private void removeAdd(int position) {
        frendBeanList.remove(position + 1);
        notifyItemRemoved(position + 1);
//        notifyItemRangeRemoved(position + 1, frendBeanList.size() - (position + 1));
    }

    /**
     * 下划线
     *
     * @param view
     * @param isChecked
     */
    private void addTextViewUnderLine(TextView view, boolean isChecked) {
        view.getPaint().setFlags(isChecked == true ?
                view.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG :
                view.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                      int viewType) {
        RecyclerView.ViewHolder myViewHolder = null;
        //根据不同的ViewType类型，来返回不同的ViewHolder
        switch (viewType) {

            case VIEW_TYPE_ONE:
                myViewHolder = new ViewHolderOne
                        (LayoutInflater.from(parent.getContext()).inflate(R.layout.new_my_header, parent, false));
                break;

            case VIEW_TYPE_TWO:
                myViewHolder = new ViewHolderTwo
                        (LayoutInflater.from(parent.getContext()).inflate(R.layout.new_my_item, parent, false));
                break;

            case VIEW_TYPE_THREE:
                myViewHolder = new ViewHolderThree
                        (LayoutInflater.from(parent.getContext()).inflate(R.layout.new_my_foolter, parent, false));
                break;

            case VIEW_TYPE_FOUR:
                myViewHolder = new ViewHolderFour
                        (LayoutInflater.from(parent.getContext()).inflate(R.layout.new_my_add_calender, parent, false));
                break;
        }

        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {

        switch (holder.getItemViewType()) {

            case VIEW_TYPE_ONE:

                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showStubImage(R.mipmap.img_null_smal)          // 设置图片下载期间显示的图片
                        .showImageForEmptyUri(R.mipmap.img_null_smal)  // 设置图片Uri为空或是错误的时候显示的图片
                        .showImageOnFail(R.mipmap.img_null_smal)       // 设置图片加载或解码过程中发生错误显示的图片
                        .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                        .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中
//                        .displayer(new RoundedBitmapDisplayer(20))  // 设置成圆角图片
                        .build();

                String imageurl = URLConstants.HOST+"/TbDU_showImage.htm?imageName=" + frendBeanList.get(holder.getAdapterPosition()).getF_uPortrait() + "&imageType=2&imageSizeType=3";
                ViewHolderOne holderOne = (ViewHolderOne) holder;
                if (position == 0){
                    holderOne.vt.setVisibility(View.VISIBLE);
                }else {
                    holderOne.vt.setVisibility(View.GONE);
                }
                //添加item
                holderOne.add_lll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        addPersonCalender(holder.getAdapterPosition());
//                        postPersonCalerder(position,"0",frendBeanList.get(position).getF_cpId(),0,"10000","message"+Math.random()+"");
                    }
                });

                //点击好友header
                holderOne.yc_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alterImportantDialog(holder.getAdapterPosition());
                    }
                });

                //加载图片
                ImageLoader.getInstance().displayImage(imageurl, holderOne.icon, options);
                //点击好友
                holderOne.icon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alterImportantDialog(holder.getAdapterPosition());
                    }
                });

                //判断好友是否有日程
                if (frendBeanList.get(position + 1).getViewType() == 2 || frendBeanList.get(position + 1).getViewType() == 3) {
                    holderOne.name.setTextColor(context.getResources().getColor(R.color.title0));
                    holderOne.name.setText("@" + frendBeanList.get(position).getF_uNickName());
                } else {
                    holderOne.name.setText("@" + frendBeanList.get(position).getF_uNickName());
                    holderOne.name.setTextColor(Color.parseColor("#55000000"));
                }

                holderOne.mess.setText(frendBeanList.get(position).getF_uPersontag().equals("") ? "暂无消息" : frendBeanList.get(position).getF_uPersontag());
                break;

            case VIEW_TYPE_TWO:
                final ViewHolderTwo holderTwo = (ViewHolderTwo) holder;

//                Log.e("TAG", frendBeanList.get(position).getCPostpone() + "-----==---" + frendBeanList.get(position).getRepDisplayTime());

                if (frendBeanList.get(position).getCPostpone().equals("1") && frendBeanList.get(position).getRepDisplayTime().equals("0")) {
                    holderTwo.order.setText("待办");
                } else {
                    if (frendBeanList.get(position).getRepDisplayTime().equals("1")){
                        holderTwo.order.setText(frendBeanList.get(position).getCdate().replace("T", " ").substring(5, frendBeanList.get(position).getCdate().length()) + " " +
                                frendBeanList.get(position).getCtime().replace("T", " "));
                    }else {
                        holderTwo.order.setText(frendBeanList.get(position).getCdate().replace("T", " ").substring(5, frendBeanList.get(position).getCdate().length()) + " " + "全天");
                    }

                }



                holderTwo.zti.setVisibility(View.GONE);
                holderTwo.ztt.setTextColor(Color.parseColor("#44000000"));
                if (frendBeanList.get(position).getDownNum() != null && frendBeanList.get(position).getEndNum() != null
                        && frendBeanList.get(position).getDownNum().equals("1") && !frendBeanList.get(position).getEndNum().equals("1")) {
                    holderTwo.ztt.setText("进行中");
                } else if (frendBeanList.get(position).getDownNum() != null && frendBeanList.get(position).getEndNum() != null
                        && frendBeanList.get(position).getDownNum().equals("1") && frendBeanList.get(position).getEndNum().equals("1")) {
                    holderTwo.ztt.setText("已完成");
                    holderTwo.ztt.setTextColor(context.getResources().getColor(R.color.dialog_item_text_red));
                    holderTwo.zti.setVisibility(View.VISIBLE);
                } else {
                    holderTwo.ztt.setText("未读");
                }

                holderTwo.message.setText(frendBeanList.get(position).getMessage());
                holderTwo.downnum.setText("已下行=" + frendBeanList.get(position).getDownNum());
                holderTwo.downstate.setText(frendBeanList.get(position).getEndNum() == null ? "已结束=0" : "已结束=" + frendBeanList.get(position).getEndNum());
                if (frendBeanList.get(position).getCount() > 0 && frendBeanList.get(position).getZids().equals(frendBeanList.get(position).getId())) {
                    holderTwo.calender_type.setVisibility(View.VISIBLE);
                } else {
                    holderTwo.calender_type.setVisibility(View.GONE);
                }
                //删除item
                holderTwo.llc.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        SwipeLayout.shrinkAllView();
                        deleteItem(holder.getAdapterPosition());
                        return false;
                    }
                });
//                holderTwo.radioButton.setTag(new Integer(position));//设置tag 否则划回来时选中消失
                //checkbox  复用问题
//                holderTwo.radioButton.setOnCheckedChangeListener(null);
                holderTwo.radioButton.setChecked(frendBeanList.get(position).getPoststate().equals("2") ? true : false);
                //删除线
                //   addTextViewUnderLine(holderTwo.message, frendBeanList.get(position).getPoststate().equals("2") ? true : false);
                //item背景
                holderTwo.l_c.setBackground(frendBeanList.get(position).getPoststate().equals("2") ?
                        context.getResources().getDrawable(R.drawable.item) :
                        context.getResources().getDrawable(R.drawable.item));
                holderTwo.message.setTextColor(frendBeanList.get(position).getPoststate().equals("2") ? Color.parseColor("#44000000") : Color.parseColor("#000000"));

                holderTwo.radioButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(System.currentTimeMillis());

                        Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
                        vib.vibrate(100);
                        String poststate = frendBeanList.get(position).getPoststate();
                        if (frendBeanList.get(position).getPoststate().equals("0")) {
                            postPersonCalerder(holder.getAdapterPosition(), "2", frendBeanList.get(holder.getAdapterPosition()).getCpId(), 2, frendBeanList.get(holder.getAdapterPosition()).getId(), frendBeanList.get(holder.getAdapterPosition()).getMessage(), simpleDateFormat.format(date));
                        } else {
                            postPersonCalerder(holder.getAdapterPosition(), "0", frendBeanList.get(holder.getAdapterPosition()).getCpId(), 2, frendBeanList.get(holder.getAdapterPosition()).getId(), frendBeanList.get(holder.getAdapterPosition()).getMessage(), simpleDateFormat.format(date));
                        }
                    }
                });

                holderTwo.item_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        frendBeanList.get(holder.getAdapterPosition()).setCount(0);
                        notifyItemChanged(holder.getAdapterPosition());
                        send3(6, Integer.valueOf(frendBeanList.get(holder.getAdapterPosition()).getId())
                                , Integer.valueOf(frendBeanList.get(holder.getAdapterPosition()).getCpId()), holder.getAdapterPosition());
                        intentLy(holder.getAdapterPosition());
                    }
                });
                break;

            case VIEW_TYPE_THREE:

//                Log.e("TAG", frendBeanList.get(position).getCPostpone() + "--------" + frendBeanList.get(position).getRepDisplayTime());

                final ViewHolderThree holderThree = (ViewHolderThree) holder;

                if (frendBeanList.get(position).getCPostpone().equals("1") && frendBeanList.get(position).getRepDisplayTime().equals("0")) {
                    holderThree.order.setText("待办");
                } else {
                    if (frendBeanList.get(position).getRepDisplayTime().equals("1")) {
                        holderThree.order.setText(frendBeanList.get(position).getCdate().replace("T", " ").substring(5, frendBeanList.get(position).getCdate().length()) + " " +
                                frendBeanList.get(position).getCtime().replace("T", " "));
                    } else {
                        holderThree.order.setText(frendBeanList.get(position).getCdate().replace("T", " ").substring(5, frendBeanList.get(position).getCdate().length()) + " " + "全天");
                    }
                }

                holderThree.zti.setVisibility(View.GONE);
                holderThree.ztt.setTextColor(Color.parseColor("#44000000"));
                if (frendBeanList.get(position).getDownNum() != null && frendBeanList.get(position).getEndNum() != null
                        && frendBeanList.get(position).getDownNum().equals("1") && !frendBeanList.get(position).getEndNum().equals("1")) {
                    holderThree.ztt.setText("进行中");
                } else if (frendBeanList.get(position).getDownNum() != null && frendBeanList.get(position).getEndNum() != null
                        && frendBeanList.get(position).getDownNum().equals("1") && frendBeanList.get(position).getEndNum().equals("1")) {
                    holderThree.ztt.setText("已完成");
                    holderThree.ztt.setTextColor(context.getResources().getColor(R.color.dialog_item_text_red));
                    holderThree.zti.setVisibility(View.VISIBLE);
                } else {
                    holderThree.ztt.setText("未读");
                }

                holderThree.message.setText(frendBeanList.get(position).getMessage());

                holderThree.downnum.setText("已下行=" + frendBeanList.get(position).getDownNum());
                holderThree.downstate.setText(frendBeanList.get(position).getEndNum() == null ? "已结束=0" : "已结束=" + frendBeanList.get(position).getEndNum());
                //删除item
                holderThree.llc.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        SwipeLayout.shrinkAllView();
                        deleteItem(holder.getAdapterPosition());

                        return false;
                    }
                });
                if (frendBeanList.get(position).getCount() > 0 && frendBeanList.get(position).getZids().equals(frendBeanList.get(position).getId())) {
                    holderThree.calender_type.setVisibility(View.VISIBLE);
                } else {
                    holderThree.calender_type.setVisibility(View.GONE);
                }
//                holderThree.radioButton.setTag(new Integer(position));//设置tag 否则划回来时选中消失
                //checkbox  复用问题
                holderThree.radioButton.setChecked(frendBeanList.get(holder.getAdapterPosition()).getPoststate().equals("2") ? true : false);
                //删除线
                //addTextViewUnderLine(holderThree.message, frendBeanList.get(position).getPoststate().equals("2") ? true : false);
                //item背景
                holderThree.l_c.setBackground(frendBeanList.get(position).getPoststate().equals("2") ?
                        context.getResources().getDrawable(R.drawable.foolter) :
                        context.getResources().getDrawable(R.drawable.foolter));
                holderThree.message.setTextColor(frendBeanList.get(position).getPoststate().equals("2") ? Color.parseColor("#44000000") : Color.parseColor("#000000"));
                holderThree.radioButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(System.currentTimeMillis());

                        Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
                        vib.vibrate(100);
                        //frendBeanList.get(holder.getAdapterPosition()).getPoststate().equals("2") == true
                        String poststate = frendBeanList.get(position).getPoststate();
                        if (frendBeanList.get(position).getPoststate().equals("0")) {
                            postPersonCalerder(holder.getAdapterPosition(), "2", frendBeanList.get(holder.getAdapterPosition()).getCpId(), 2, frendBeanList.get(holder.getAdapterPosition()).getId(), frendBeanList.get(holder.getAdapterPosition()).getMessage(), simpleDateFormat.format(date));
                        } else {
                            postPersonCalerder(holder.getAdapterPosition(), "0", frendBeanList.get(holder.getAdapterPosition()).getCpId(), 2, frendBeanList.get(holder.getAdapterPosition()).getId(), frendBeanList.get(holder.getAdapterPosition()).getMessage(), simpleDateFormat.format(date));
                        }
                    }
                });

                holderThree.item_ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        frendBeanList.get(holder.getAdapterPosition()).setCount(0);
                        notifyItemChanged(holder.getAdapterPosition());
                        send3(6, Integer.valueOf(frendBeanList.get(holder.getAdapterPosition()).getId())
                                , Integer.valueOf(frendBeanList.get(holder.getAdapterPosition()).getCpId())
                                , holder.getAdapterPosition());
                        intentLy(holder.getAdapterPosition());
                    }
                });

//                if ((position + 1) == frendBeanList.size()) {
//                    LinearLayout.LayoutParams lp =
//                            new LinearLayout.LayoutParams(
//                                    LinearLayout.LayoutParams.MATCH_PARENT,
//                                    LinearLayout.LayoutParams.WRAP_CONTENT);
//                    lp.setMargins(0, 0, 49, 60);
//                    holderThree.l_c.setLayoutParams(lp);
//
//                }
                break;

            case VIEW_TYPE_FOUR:
                ViewHolderFour holderFour = (ViewHolderFour) holder;
                //添加item
                holderFour.add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        addPersonCalender(holder.getAdapterPosition() - 1);
//                        postPersonCalerder(position,"0",frendBeanList.get(position).getF_cpId(),0,"10000","message"+Math.random()+"");
                    }
                });
//                if ((position + 1) == frendBeanList.size()) {
//                    LinearLayout.LayoutParams lp =
//                            new LinearLayout.LayoutParams(
//                                    LinearLayout.LayoutParams.MATCH_PARENT,
//                                    200);
//                    lp.setMargins(0, 0, 49, 60);
//                    holderFour.bottom_l.setLayoutParams(lp);
//                    holderFour.bottom_l.setBackground(context.getResources().getDrawable(R.drawable.add));
//                }
                break;
        }
    }

    private void postPersonCalerder(int position, String poststate, String cpid, int type, String id, String message, String time) {
        if (type == 0) {
            progressUtil.ShowProgress(context, true, true, "日程添加中...");
        }
        if (type == 1) {
            progressUtil.ShowProgress(context, true, true, "日程删除中...");
        }
        if (type == 2) {
            progressUtil.ShowProgress(context, true, true, "日程修改中...");
        }

        SharedPrefUtil sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);

        PersonCalerder(frendBeanList.get(position), poststate, type, cpid, id,
                frendBeanList.get(position).getUid(),
                time,
                sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""),
                frendBeanList.get(position).getF_uNickName(),
                message,
                frendBeanList.get(position).getF_uPortrait(),
                position
        );
    }

    /**
     * 跳转日程详情页面
     */
    private void intentLy(int position) {
        Intent intent = new Intent(context, FrendLyActivity.class);
        Bundle bundle = new Bundle();
//        intent.putExtra("message", frendBeanList.get(position).getMessage());
//        intent.putExtra("icon", frendBeanList.get(position).getF_uPortrait());
//        intent.putExtra("name", frendBeanList.get(position).getF_uNickName());
//        intent.putExtra("time", frendBeanList.get(position).getChangTime());
//        intent.putExtra("cid", frendBeanList.get(position).getId());
        //   Log.d("dddddd", ">>>>>>>>>>:" + frendBeanList.get(position));
        FrendBean frendBean = frendBeanList.get(position);

        bundle.putSerializable("schedule", frendBean);
        intent.putExtra("message", frendBeanList.get(position).getMessage());
        intent.putExtra("name", frendBeanList.get(position).getF_uNickName());
        intent.putExtra("change_time", frendBeanList.get(position).getCretetime());
        intent.putExtra("cid", frendBeanList.get(position).getId());
        intent.putExtra("uid", frendBeanList.get(position).getUid());
        intent.putExtra("remark", (String) frendBeanList.get(position).getF_remark());
        intent.putExtra("uToCode", frendBeanList.get(position).getF_uToCode());
        intent.putExtra("uBackgroundImage", frendBeanList.get(position).getF_uBackgroundImage());
        intent.putExtra("id", frendBeanList.get(position).getF_id());
        intent.putExtra("uPortrait", frendBeanList.get(position).getF_uPortrait());
        intent.putExtra("cType", frendBeanList.get(position).getF_type());
        intent.putExtra("remark1", frendBeanList.get(position).getRemark1());
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    private void send(int position, String uid) {
        Message me = new Message();
        me.what = position;
        me.arg1 = Integer.valueOf(uid);
        handler.sendMessage(me);
    }

    private void send3(int what, int id, int cpid, int position) {
        Message me = new Message();
        me.what = what;
        me.arg1 = id;
        me.arg2 = cpid;
        me.obj = position;
        handler.sendMessage(me);
    }

    Handler handler;


    /**
     * item数量
     *
     * @return
     */
    @Override
    public int getItemCount() {
        return frendBeanList.size();
    }


    /**
     * item类型
     *
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        return frendBeanList.get(position).getViewType();
    }


    /**
     * 删除日程
     *
     * @param position
     */
    private void deleteItem(final int position) {
        final android.app.AlertDialog builder = new android.app.AlertDialog.Builder(context)
                .create();

        builder.show();
        Window window = builder.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alterdelete);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        TextView delete_canel = (TextView) window
                .findViewById(R.id.delete_canel);
        delete_canel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);

        delete_tv.setText("确定要删除此日程吗?");

        delete_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
//                SharedPrefUtil sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
//                PersonCalerder(frendBeanList.get(position), frendBeanList.get(position).poststate, 1,
//                        frendBeanList.get(position).getF_cpId(), frendBeanList.get(position).getId(),
//                        frendBeanList.get(position).getUid(),
//                        simpleDateFormat.format(date),
//                        sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""),
//                        frendBeanList.get(position).getF_uNickName(),
//                        frendBeanList.get(position).getMessage(),
//                        frendBeanList.get(position).getF_uPortrait(),
//                        position
//                );
                postPersonCalerder(position, frendBeanList.get(position).poststate,
                        frendBeanList.get(position).getCpId(), 1, frendBeanList.get(position).getId(),
                        frendBeanList.get(position).getMessage(), simpleDateFormat.format(date));
                builder.dismiss();
            }
        });
    }

    /**
     * 隐藏好友对话框-提醒用户清除任务
     */
    private void deleteUserTitle() {
        final android.app.AlertDialog builder = new android.app.AlertDialog.Builder(context)
                .create();

        builder.show();
        Window window = builder.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alert_ok);
        TextView delete_ok = (TextView) window
                .findViewById(R.id.delete_ok);
        delete_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);

        delete_tv.setText("隐藏好友需要清除全部任务!");

    }

    /**
     * 隐藏好友对话框
     */
    private void deleteCalender(final int position) {
        final android.app.AlertDialog builder = new android.app.AlertDialog.Builder(context)
                .create();

        builder.show();
        Window window = builder.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alter);
        TextView delete_ok = (TextView) window
                .findViewById(R.id.delete_ok);
        delete_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                deleteFriendAnswer(frendBeanList.get(position).getF_uid(), frendBeanList.get(position).getF_cpId(), position);
                builder.dismiss();
            }
        });
        window.findViewById(R.id.cancle_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);

        delete_tv.setText("确定隐藏该好友!");

    }


    /**
     * 点击header,弹出隐藏，取消布局
     */
    private void alterImportantDialog(int position) {
        Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.new_my_yc_dialog, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.show();

        new alterImportantDialogOnClick(dialog, more_pop_menu, position);
    }

    /**
     * 点击header 点击事件
     */
    class alterImportantDialogOnClick implements View.OnClickListener {

        private View view;
        private Dialog dialog;
        private TextView yc_tv;
        private TextView canel_tv;
        private int Position;

        @SuppressLint("NewApi")
        public alterImportantDialogOnClick(Dialog dialog, View view, final int position) {
            this.dialog = dialog;
            this.view = view;
            this.Position = position;
            initview();
        }

        private void initview() {
            yc_tv = (TextView) view.findViewById(R.id.yc_tv);
            yc_tv.setOnClickListener(this);
            canel_tv = (TextView) view.findViewById(R.id.canel_tv);
            canel_tv.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.yc_tv:
                    if (frendBeanList.get(Position + 1).getViewType() == 4) {
                        deleteCalender(Position);
                    } else {
                        deleteUserTitle();
                    }
                    dialog.dismiss();
                    break;
                case R.id.canel_tv:
                    dialog.dismiss();
                    break;
            }
        }
    }

    /**
     * 修改日程状态
     *
     * @param position
     * @param id
     * @param poststate
     */
    private void postState(int position, String id, String poststate) {

        App.getDBcApplication().updateFriendScheduleType(id, poststate);

        frendBeanList.get(position).setPoststate(poststate);

        notifyItemChanged(position);

        progressUtil.dismiss();

    }

    /**
     * 添加用户日程dialog
     *
     * @param position
     */
    private void addPersonCalender(int position) {
        Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 1f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_add_person_calender, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;

        new alterAddDialogOnClick(dialog, more_pop_menu, position);
    }

    /**
     * 添加用户日程dialog,点击事件
     */
    class alterAddDialogOnClick implements View.OnClickListener {

        private View view;
        private Dialog dialog;
        private TextView name, time, cancel, ok;
        private Button wancheng;
        TextView zt, db;
        private EditText content;
        private LinearLayout pickter_ll;

        private DatePicker dp_test;
        private TimePicker tp_test;

        final int position;
        private String selectDate, selectTime;
        private boolean contenttype = false;

        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        final Date date = new Date(System.currentTimeMillis());

        @SuppressLint("NewApi")
        public alterAddDialogOnClick(Dialog dialog, View view, int position) {
            this.dialog = dialog;
            this.view = view;
            this.position = position;
            initview();
            //滚动组布局

            dialog.show();
        }


        private void initview() {

            selectDate = simpleDateFormat.format(date).substring(0, 10);
            selectTime = simpleDateFormat.format(date).substring(11, 16);
            name = (TextView) view.findViewById(R.id.name);
            zt = (TextView) view.findViewById(R.id.zt);
            wancheng = (Button) view.findViewById(R.id.wancheng);
            content = (EditText) view.findViewById(R.id.content);
            content.setImeOptions(EditorInfo.IME_ACTION_SEND);
            time = (TextView) view.findViewById(R.id.time);
            pickter_ll = (LinearLayout) view.findViewById(R.id.pickter_ll);
            cancel = (TextView) view.findViewById(R.id.cancel);
            ok = (TextView) view.findViewById(R.id.ok);
            db = (TextView) view.findViewById(R.id.db);
            dp_test = (DatePicker) view.findViewById(R.id.dp_test);
            tp_test = (TimePicker) view.findViewById(R.id.tp_test);

            //设置滑动改变监听器
            dp_test.setOnChangeListener(dp_onchanghelistener);
            tp_test.setOnChangeListener(tp_onchanghelistener);

            name.setText("@" + frendBeanList.get(position).getF_uNickName());

            time.setText(simpleDateFormat.format(date));
            content.setFocusable(true);


            //打开软键盘
            imm.showSoftInput(content, 0);
            content.setOnClickListener(this);
            cancel.setOnClickListener(this);
            ok.setOnClickListener(this);
            zt.setOnClickListener(this);
            time.setOnClickListener(this);
            wancheng.setOnClickListener(this);
            db.setOnClickListener(this);
            /** 3.自动弹出软键盘 **/
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                public void onShow(DialogInterface dialog) {
                    pickter_ll.setVisibility(View.GONE);
                    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(content, InputMethodManager.SHOW_IMPLICIT);
                }
            });
        }


        //listeners
        DatePicker.OnChangeListener dp_onchanghelistener = new DatePicker.OnChangeListener() {
            @Override
            public void onChange(int year, int month, int day, int day_of_week) {
                selectDate = year + "-" + ((month < 10) ? "0" + month : month) + "-" + ((day < 10) ? "0" + day : day);
                time.setText(selectDate + " " + selectTime);
            }
        };
        TimePicker.OnChangeListener tp_onchanghelistener = new TimePicker.OnChangeListener() {
            @Override
            public void onChange(int hour, int minute) {
                selectTime = ((hour < 10) ? ("0" + hour) : hour) + ":" + ((minute < 10) ? ("0" + minute) : minute);
                time.setText(selectDate + " " + selectTime);
            }
        };


        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                //TODO
                case R.id.wancheng:
                    if (NetUtil.getConnectState(context) != NetUtil.NetWorkState.NONE) {
                        if (!content.getText().toString().trim().equals("") || !TextUtils.isEmpty(content.getText().toString())) {
                            postPersonCalerder(position, "0", frendBeanList.get(position).getF_cpId(), 0, "10000", content.getText().toString(), time.getText().toString() + ":00");
                            dialog.dismiss();
                        } else {
                            Toast.makeText(context, "日程内容不能为空!", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.ok:
                    time.setTextColor(Color.parseColor("#30a9a0"));
                    //打开软键盘
                    imm.showSoftInput(content, 0);
                    pickter_ll.setVisibility(View.GONE);
                    cpost = 0;
                    contenttype = true;
                    displayAlarm = 1;
                    db.setTextColor(context.getResources().getColor(R.color.gray));
                    break;
                case R.id.cancel:
                    dialog.dismiss();
                    break;
                case R.id.zt:
                    //粘贴
                    ClipboardManager myClipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData abc = myClipboard.getPrimaryClip();
                    if (abc != null) {
                        ClipData.Item item = abc.getItemAt(0);
                        content.setText(content.getText().toString() + "" + item.getText().toString());
                        //修改光标位置
                        content.setSelection(content.getText().toString().length());
                    }

                    break;
                case R.id.time:
                    db.setTextColor(Color.parseColor("#555555"));
                    time.setTextColor(Color.parseColor("#30a9a0"));
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘

                    pickter_ll.setVisibility(View.VISIBLE);
                    break;
                case R.id.content:
                    if (contenttype == false) {
                        cpost = 1;
                        displayAlarm = 0;
                    }
                    if (cpost == 1) {
                        time.setTextColor(Color.parseColor("#555555"));
                        db.setTextColor(Color.parseColor("#30a9a0"));
                    }
                    pickter_ll.setVisibility(View.GONE);
                    imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
                    break;
                case R.id.db:
                    contenttype = false;
                    cpost = 1;
                    pickter_ll.setVisibility(View.GONE);
                    db.setTextColor(Color.parseColor("#30a9a0"));
                    time.setTextColor(Color.parseColor("#555555"));
                    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(content, InputMethodManager.SHOW_IMPLICIT);
                    break;
            }
        }
    }

    /**
     * 对好友日程进行操作
     *
     * @param frendBean
     * @param poststate 2关闭 0打开
     * @param type      操作类型  0 添加 1删除  2修改
     * @param cpid
     * @param calendaId
     * @param uid
     * @param time
     * @param name
     * @param nickname
     * @param message
     * @param uPortrait
     * @param position
     */
    private void PersonCalerder(final FrendBean frendBean, final String poststate, final int type, final String cpid, final String calendaId, final String uid, final String time, final String name, final String nickname, final String message, final String uPortrait, final int position) {

        final JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            //添加的json
            if (type == 0) {
                jsonObject.put("CAlarmsound", "g_220");
                jsonObject.put("CAlarmsoundDesc", "短提示音");
                jsonObject.put("CLightAppId", 0);
                jsonObject.put("COpenstate", 0);
                jsonObject.put("CPostpone", cpost);
                jsonObject.put("CRecommendName", name);
                jsonObject.put("CTags", "");
                jsonObject.put("CType", 0);
                jsonObject.put("CTypeDesc", "");
                jsonObject.put("CTypeSpare", "");
                jsonObject.put("calendaId", 0);
                jsonObject.put("cbeforTime", 0);
                jsonObject.put("cdate", time.substring(0, 10));
                jsonObject.put("changTime", time);
                jsonObject.put("cisAlarm", 1);
                jsonObject.put("cpId", cpid);
                jsonObject.put("cretetime", time);
                jsonObject.put("ctime", time.substring(11, 16));

                jsonObject.put("atype", 0);
                jsonObject.put("downNum", 0);
                jsonObject.put("downstate", 0);
                jsonObject.put("endNum", 0);
                jsonObject.put("endState", "0");
                jsonObject.put("id", Integer.valueOf(calendaId));
                jsonObject.put("imgPath", "");
                jsonObject.put("lyNum", 0);
                jsonObject.put("message", message);
                jsonObject.put("parReamrk", "");
                jsonObject.put("pid", "");
                jsonObject.put("poststate", "0");
                jsonObject.put("remark", "");
                jsonObject.put("remark1", android.os.Build.MANUFACTURER+" "+android.os.Build.MODEL);
                jsonObject.put("remark2", "");
                jsonObject.put("remark3", "");
                jsonObject.put("repCalendaState", 0);
                jsonObject.put("repCalendaTime", "");
                jsonObject.put("repColorType", 0);
                jsonObject.put("repDisplayTime", displayAlarm);
                jsonObject.put("repInStable", 1);
                jsonObject.put("repIsPuase", 0);
                jsonObject.put("repState", 0);
                jsonObject.put("repType", 0);
                jsonObject.put("repTypeParameter", "");
                jsonObject.put("repdatetwo", "");
                jsonObject.put("repinitialcreatedtime", "");
                jsonObject.put("replastcreatedtime", "");
                jsonObject.put("repnextcreatedtime", "");
                jsonObject.put("repstartdate", "");

                jsonObject.put("repstatetwo", 0);
                jsonObject.put("schIsImportant", 0);
                jsonObject.put("status", 1);
                jsonObject.put("uid", Integer.valueOf(uid));
                jsonObject.put("webUrl", "");
            }


            //删除和修改的json
            if (type == 1 || type == 2) {
                jsonObject.put("CAlarmsound", frendBean.CAlarmsound);
                jsonObject.put("CAlarmsoundDesc", frendBean.CAlarmsoundDesc);
                jsonObject.put("CLightAppId", frendBean.CLightAppId == null ? 0 : Integer.valueOf(frendBean.CLightAppId));
                jsonObject.put("COpenstate", frendBean.COpenstate == null ? 0 : Integer.valueOf(frendBean.COpenstate));
                jsonObject.put("CPostpone", frendBean.CPostpone == null ? 0 : Integer.valueOf(frendBean.CPostpone));
                jsonObject.put("CRecommendName", frendBean.CRecommendName);
                jsonObject.put("CTags", frendBean.CTags);
                jsonObject.put("CType", frendBean.CType == null ? 0 : Integer.valueOf(frendBean.CType));
                jsonObject.put("CTypeDesc", frendBean.CTypeDesc);
                jsonObject.put("CTypeSpare", frendBean.CTypeSpare);
                jsonObject.put("calendaId", frendBean.calendaId == null ? 0 : Integer.valueOf(frendBean.calendaId));
                jsonObject.put("cbeforTime", frendBean.cbeforTime == null ? 0 : Integer.valueOf(frendBean.cbeforTime));
                jsonObject.put("cdate", time.substring(0, 10));
                jsonObject.put("changTime", time);
                jsonObject.put("cisAlarm", Integer.valueOf(frendBean.cisAlarm));
                jsonObject.put("cpId", cpid);
                jsonObject.put("cretetime", frendBean.cretetime.replace('T', ' '));
                jsonObject.put("ctime", time.substring(11, 16));

                jsonObject.put("atype", Integer.valueOf(frendBean.atype));
                jsonObject.put("downNum", Integer.valueOf(frendBean.downNum));
                jsonObject.put("downstate", Integer.valueOf(frendBean.downstate));
                jsonObject.put("endNum", frendBean.endNum == null ? 0 : Integer.valueOf(frendBean.endNum));
                jsonObject.put("endState", frendBean.endState);
                jsonObject.put("id", Integer.valueOf(calendaId));
                jsonObject.put("imgPath", frendBean.imgPath);
                jsonObject.put("lyNum", Integer.valueOf(frendBean.lyNum));
                jsonObject.put("message", message);
                jsonObject.put("parReamrk", frendBean.parReamrk);
                jsonObject.put("pid", frendBean.pid);
                jsonObject.put("poststate", poststate);//2关闭   0打开
                jsonObject.put("remark", frendBean.remark);
                jsonObject.put("remark1", frendBean.remark1);
                jsonObject.put("remark2", frendBean.remark2);
                jsonObject.put("remark3", frendBean.remark3);
                jsonObject.put("repCalendaState", Integer.valueOf(frendBean.repCalendaState));
                jsonObject.put("repCalendaTime", frendBean.repCalendaTime);
                jsonObject.put("repColorType", Integer.valueOf(frendBean.repColorType));
                jsonObject.put("repDisplayTime", Integer.valueOf(frendBean.repDisplayTime));
                jsonObject.put("repInStable", Integer.valueOf(frendBean.repInStable));
                jsonObject.put("repIsPuase", Integer.valueOf(frendBean.repIsPuase));
                jsonObject.put("repState", frendBean.repState.equals("") ? 0 : Integer.valueOf(frendBean.repState));
                jsonObject.put("repType", Integer.valueOf(frendBean.repType));
                jsonObject.put("repTypeParameter", frendBean.repTypeParameter);
                jsonObject.put("repdatetwo", frendBean.repdatetwo);
                jsonObject.put("repinitialcreatedtime", frendBean.repinitialcreatedtime);
                jsonObject.put("replastcreatedtime", frendBean.replastcreatedtime);
                jsonObject.put("repnextcreatedtime", frendBean.repnextcreatedtime);
                jsonObject.put("repstartdate", frendBean.repstartdate);

                jsonObject.put("repstatetwo", frendBean.repstatetwo == null ? 0 : Integer.valueOf(frendBean.repstatetwo));
                jsonObject.put("schIsImportant", Integer.valueOf(frendBean.schIsImportant));
                jsonObject.put("status", Integer.valueOf(frendBean.status));
                jsonObject.put("uid", Integer.valueOf(uid));
                jsonObject.put("webUrl", frendBean.webUrl);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonArray.put(jsonObject);

        Log.e("TAG", jsonArray.toString());

        //192.168.2.2:8080 周伟
        StringRequest stringRequest = new StringRequest(Request.Method.POST,URLConstants.HOST+"/appFrends_synFrendCalendaNew.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();
                                Log.e("TAG", result);
                                PersonCalerder personCalerder = gson.fromJson(result, PersonCalerder.class);
                                if (personCalerder.status == 0) {
                                    List<PersonCalerderListBean> personCalerderListBeanList = personCalerder.list;
                                    if (personCalerderListBeanList.get(0).getState() == 0) {
                                        if (type == 0) {
                                            addData(cpid, uid, time, personCalerderListBeanList.get(0).calendId + "", name, message, nickname, uPortrait, position);
                                        } else if (type == 1) {
                                            deleteitem(personCalerderListBeanList.get(0).calendId + "", position);
                                        } else if (type == 2) {
                                            postState(position, personCalerderListBeanList.get(0).calendId + "", poststate);
                                        }
                                    } else {
                                        Log.d("TAG", "error:1");
                                        progressUtil.dismiss();
                                        notifyItemChanged(position);
                                        Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Log.d("TAG", "error:2");
                                    progressUtil.dismiss();
                                    notifyItemChanged(position);
                                    Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                Log.d("TAG", "error:3");
                                progressUtil.dismiss();
                                notifyItemChanged(position);
                                Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
                progressUtil.dismiss();
                notifyItemChanged(position);
                Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                //添加
                if (type == 0) {
                    map.put("data", "{addData:" + jsonArray.toString() + ",updateData:[],deleData:[]}");
                }
                //删除
                if (type == 1) {
                    map.put("data", "{addData:[],updateData:[] ,deleData:" + jsonArray.toString() + "}");
                }
                //修改
                if (type == 2) {
                    map.put("data", "{addData:[],updateData:" + jsonArray.toString() + ",deleData:[]}");
                }
                return map;
            }
        };
        stringRequest.setTag("synFrendCalendaNew");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    /**
     * 删除数据库
     *
     * @param calendId
     * @param position
     */
    private void deleteitem(String calendId, int position) {
        App.getDBcApplication().deleteFriendSchedule(calendId);

        removeData(position);
    }


    /**
     * 隐藏用户
     *
     * @param uid
     * @param cpid
     */
    public void deleteFriendAnswer(final String uid, final String cpid, final int position) {

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                URLConstants.HOST+"/appFrends_delFrendsSay.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String request) {

                        if (!TextUtils.isEmpty(request)) {
                            try {
                                if (responseCode(request)) {
                                    deleteSQLFriend(cpid, position);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> map = new HashMap<String, String>();
                map.put("uId", uid);
                map.put("fId", cpid);
                map.put("type", "2");
                return map;
            }


        };
        stringRequest.setTag("delFrendsSay");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);

    }

    /***
     * 是否返回成功
     *
     * @param response
     * @return
     * @throws JSONException
     */
    public boolean responseCode(String response) throws JSONException {
        int status = 0;
        JSONObject jsonObject = new JSONObject(response);
        int msg = jsonObject.getInt("status");
        return status == msg;
    }


    /**
     * 删除用户数据库操作
     */
    private void deleteSQLFriend(String cpid, int position) {
        App.getDBcApplication().deleteFriend(cpid);

        deleteUserList(position);
    }

    /**
     * 删除用户list
     */
    private void deleteUserList(int position) {
        frendBeanList.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeRemoved(position, frendBeanList.size() - position);

        frendBeanList.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeRemoved(position, frendBeanList.size() - position);

        Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();


        if (frendBeanList.size() == 0){
            send(8,"1");
        }
    }


    /**
     * 添加日程
     *
     * @param cpid
     * @param uid
     * @param time
     * @param calendId
     * @param name
     * @param message
     * @param nickname
     * @param uPortrait
     * @param viewtype
     * @param position
     */
    private void addItem(String cpid, String uid, String time, String calendId, String name, String message, String nickname, String uPortrait, int viewtype, int position) {
        FriendDownAllScheduleBean friendDownAllScheduleBean = new FriendDownAllScheduleBean();

        friendDownAllScheduleBean.setCAlarmsound("g_220");
        friendDownAllScheduleBean.setCAlarmsoundDesc("短提示音");
        friendDownAllScheduleBean.setCLightAppId("0");
        friendDownAllScheduleBean.setCOpenstate("1");
        friendDownAllScheduleBean.setCPostpone("" + cpost);
        friendDownAllScheduleBean.setCRecommendName(name);
        friendDownAllScheduleBean.setCTags("");
        friendDownAllScheduleBean.setCType("0");
        friendDownAllScheduleBean.setCTypeDesc("");
        friendDownAllScheduleBean.setCTypeSpare("");
        friendDownAllScheduleBean.setCalendaId("0");
        friendDownAllScheduleBean.setCbeforTime("0");
        friendDownAllScheduleBean.setCdate(time.substring(0, 10));
        friendDownAllScheduleBean.setChangTime(time);
        friendDownAllScheduleBean.setCisAlarm("0");
        friendDownAllScheduleBean.setCpId(cpid);
        friendDownAllScheduleBean.setCretetime(time);
        friendDownAllScheduleBean.setCtime(time.substring(11, 16));

        friendDownAllScheduleBean.setAtype("0");

        friendDownAllScheduleBean.setDownNum("0");
        friendDownAllScheduleBean.setDownstate("0");

        friendDownAllScheduleBean.setEndNum("0");
        friendDownAllScheduleBean.setEndState("0");

        friendDownAllScheduleBean.setId(calendId);
        friendDownAllScheduleBean.setImgPath("");
        friendDownAllScheduleBean.setLyNum("0");
        friendDownAllScheduleBean.setMessage(message);

        friendDownAllScheduleBean.setParReamrk("");
        friendDownAllScheduleBean.setPoststate("0");
        friendDownAllScheduleBean.setPid("");

        friendDownAllScheduleBean.setRemark("");
        friendDownAllScheduleBean.setRemark1(android.os.Build.MANUFACTURER+" "+android.os.Build.MODEL);
        friendDownAllScheduleBean.setRemark2("");
        friendDownAllScheduleBean.setRemark3("");
        friendDownAllScheduleBean.setRepCalendaState("0");
        friendDownAllScheduleBean.setRepCalendaTime("0");
        friendDownAllScheduleBean.setRepColorType("0");
        friendDownAllScheduleBean.setRepDisplayTime(""+displayAlarm);
        friendDownAllScheduleBean.setRepInStable("0");
        friendDownAllScheduleBean.setRepIsPuase("0");
        friendDownAllScheduleBean.setRepState("0");
        friendDownAllScheduleBean.setRepType("0");
        friendDownAllScheduleBean.setRepTypeParameter("");
        friendDownAllScheduleBean.setRepdatetwo("0");
        friendDownAllScheduleBean.setRepinitialcreatedtime("");
        friendDownAllScheduleBean.setReplastcreatedtime("");
        friendDownAllScheduleBean.setRepnextcreatedtime("");
        friendDownAllScheduleBean.setRepstartdate("");
        friendDownAllScheduleBean.setRepState("");

        friendDownAllScheduleBean.setSchIsImportant("0");
        friendDownAllScheduleBean.setStatus("1");

        friendDownAllScheduleBean.setUid(uid);
        friendDownAllScheduleBean.setWebUrl("");


        App.getDBcApplication().insertFriendSchedule(friendDownAllScheduleBean);


        FrendBean frendBean = new FrendBean();
        frendBean.setF_uNickName(nickname);
        frendBean.setF_uPortrait(uPortrait);
        frendBean.setViewType(viewtype);

        Log.e("TAG", "Add viewtype :" + viewtype);

        frendBean.setCAlarmsound(friendDownAllScheduleBean.CAlarmsound);
        frendBean.setCAlarmsoundDesc(friendDownAllScheduleBean.CAlarmsoundDesc);
        frendBean.setCLightAppId(friendDownAllScheduleBean.CLightAppId);
        frendBean.setCOpenstate(friendDownAllScheduleBean.COpenstate);
        frendBean.setCPostpone(friendDownAllScheduleBean.CPostpone);
        frendBean.setCRecommendName(friendDownAllScheduleBean.CRecommendName);
        frendBean.setCTags(friendDownAllScheduleBean.CTags);
        frendBean.setCType(friendDownAllScheduleBean.CType);
        frendBean.setCTypeSpare(friendDownAllScheduleBean.CTypeSpare);
        frendBean.setAtype(friendDownAllScheduleBean.atype);
        frendBean.setCalendaId(friendDownAllScheduleBean.calendaId);
        frendBean.setCbeforTime(friendDownAllScheduleBean.cbeforTime);
        frendBean.setCdate(friendDownAllScheduleBean.cdate);
        frendBean.setChangTime(friendDownAllScheduleBean.changTime);
        frendBean.setCisAlarm(friendDownAllScheduleBean.cisAlarm);
        frendBean.setCpId(cpid);
        frendBean.setCretetime(friendDownAllScheduleBean.cretetime);
        frendBean.setCtime(friendDownAllScheduleBean.ctime);
        frendBean.setDownNum(friendDownAllScheduleBean.downNum);
        frendBean.setDownstate(friendDownAllScheduleBean.downstate);
        frendBean.setId(friendDownAllScheduleBean.id);
        frendBean.setImgPath(friendDownAllScheduleBean.imgPath);
        frendBean.setLyNum(friendDownAllScheduleBean.lyNum);
        frendBean.setMessage(friendDownAllScheduleBean.message);
        frendBean.setParReamrk(friendDownAllScheduleBean.parReamrk);
        frendBean.setPoststate(friendDownAllScheduleBean.poststate);
        frendBean.setPid(friendDownAllScheduleBean.pid);
        frendBean.setRemark(friendDownAllScheduleBean.remark);
        frendBean.setRemark1(friendDownAllScheduleBean.remark1);
        frendBean.setRemark2(friendDownAllScheduleBean.remark2);
        frendBean.setRemark3(friendDownAllScheduleBean.remark3);
        frendBean.setRepCalendaState(friendDownAllScheduleBean.repCalendaState);
        frendBean.setRepCalendaTime(friendDownAllScheduleBean.repCalendaTime);
        frendBean.setRepColorType(friendDownAllScheduleBean.repColorType);
        frendBean.setRepDisplayTime(friendDownAllScheduleBean.repDisplayTime);
        frendBean.setRepInStable(friendDownAllScheduleBean.repInStable);
        frendBean.setRepIsPuase(friendDownAllScheduleBean.repIsPuase);
        frendBean.setRepState(friendDownAllScheduleBean.repState);
        frendBean.setRepType(friendDownAllScheduleBean.repType);
        frendBean.setRepTypeParameter(friendDownAllScheduleBean.repTypeParameter);
        frendBean.setRepdatetwo(friendDownAllScheduleBean.repdatetwo);
        frendBean.setRepinitialcreatedtime(friendDownAllScheduleBean.repinitialcreatedtime);
        frendBean.setReplastcreatedtime(friendDownAllScheduleBean.replastcreatedtime);
        frendBean.setRepnextcreatedtime(friendDownAllScheduleBean.repnextcreatedtime);
        frendBean.setRepstartdate(friendDownAllScheduleBean.repstartdate);
        frendBean.setRepstartdate(friendDownAllScheduleBean.repstatetwo);
        frendBean.setSchIsImportant(friendDownAllScheduleBean.schIsImportant);
        frendBean.setStatus(friendDownAllScheduleBean.status);
        frendBean.setUid(friendDownAllScheduleBean.uid);
        frendBean.setWebUrl(friendDownAllScheduleBean.webUrl);
        frendBean.setRepState(friendDownAllScheduleBean.repState);
        frendBean.setRepState(friendDownAllScheduleBean.repState);

        frendBeanList.add(position, frendBean);
    }


    /**
     * 修改,删除,新增返回
     */
    public class PersonCalerder {

        /**
         * list : [{"id":1114,"calendId":857,"state":0,"dataState":1,"downTime":"2016-09-22 16:37:00"}]
         * message : 成功
         * status : 0
         */

        public String message;
        public int status;
        /**
         * id : 1114
         * calendId : 857
         * state : 0
         * dataState : 1
         * downTime : 2016-09-22 16:37:00
         */

        public List<PersonCalerderListBean> list;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public List<PersonCalerderListBean> getList() {
            return list;
        }

        public void setList(List<PersonCalerderListBean> list) {
            this.list = list;
        }


    }

    public class PersonCalerderListBean {
        private int id;
        private int calendId;
        private int state;
        private int dataState;
        private String downTime;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getCalendId() {
            return calendId;
        }

        public void setCalendId(int calendId) {
            this.calendId = calendId;
        }

        public int getState() {
            return state;
        }

        public void setState(int state) {
            this.state = state;
        }

        public int getDataState() {
            return dataState;
        }

        public void setDataState(int dataState) {
            this.dataState = dataState;
        }

        public String getDownTime() {
            return downTime;
        }

        public void setDownTime(String downTime) {
            this.downTime = downTime;
        }
    }


}